package com.charley.icloud.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 创建MinIO配置对应的配置类MinioConfig，并注入MinIO客户端。
 * 相关配置在application.yml文件中可以查看
 *
 * 参考链接：
 *   - https://min.io/
 *   - https://developer.aliyun.com/article/1048865
 *   - https://www.minio.org.cn
 * @author charley
 * @date 2024-04-22 10:30
 * */
@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {

    /**
     * 访问地址
     * */
    private String endpoint;
    /**
     * accessKey类似于用户ID，用于唯一标识你的账户
     * */
    private String accessKey;
    /**
     * secretKey 账户的密码
     * */
    private String secretKey;
    /**
     * 默认存储桶
     * */
    private String bucketName;

    @Bean
    public MinioClient minioClient() {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
        try {
            // 创建默认存储桶
            if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())){
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            }
        } catch (Exception e){
            e.printStackTrace();
        }

        return minioClient;
    }
}
